package com.lanou.elh.sysmanage.authority_management.web.controller;

import com.lanou.elh.sysmanage.authority_management.common.ShowIp;
import com.lanou.elh.sysmanage.authority_management.entity.Log;
import com.lanou.elh.sysmanage.authority_management.entity.User;
import com.lanou.elh.sysmanage.authority_management.mapper.LogMapper;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class UserController {

    @Autowired
    private LogMapper logMapper;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public String login(User user,HttpServletRequest request){
       /*使用shiro编写认证操作*/
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());

        //3.执行登录方法
        try{
            subject.login(token);
            HttpSession session= request.getSession();
            session.setAttribute("token",token);

        //...........................
        }
        //如果没有异常登录成功
        catch (UnknownAccountException e){
            e.printStackTrace();
            //如果有异常登录失败:用户名不存在
         return "账号不存在";
            }catch (IncorrectCredentialsException e){
            return "密码错误";

        }
        Log log=new Log();
        ShowIp ip = new ShowIp();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        ip.getIpAddr(request);
        String requestParam = request.getQueryString();
        log.setName("登录系统");
        log.setType(1);
        log.setUrl("/login");
        log.setRequestType("POST");
        log.setRequestParam(requestParam);
        log.setUser(token.getUsername());
        log.setIp(ip.getIpAddr(request));
        log.setIpInfo("辽宁 大连");
        log.setTime(123);
        log.setCreateDate(format);
        logMapper.addLog(log);
        return "登录成功";


    }

    @RequestMapping("/exit")
    @ApiOperation(value = "退出登录")
    public void exit(HttpServletRequest request){
        HttpSession session= request.getSession();
        session.invalidate();
    }
}
